//嘿嘿抄的喵喵的
import plugin from '../../../lib/plugins/plugin.js'
import {exec} from 'child_process'

let timer
const _path = process.cwd()

export class update extends plugin {
    constructor() {
        super({
            name    : '更新',
            dsc     : '#更新|强制更新',
            event   : 'message',
            priority: 5000,
            rule    : [
                {
                    reg: '^互殴(强制)*更新',
                    fnc: 'update'
                }
            ]
        })

        this.typeName = 'fisticuffs-plugin'
    }


    async update(e) {

        if (!this.e.isMaster) {
            return false
        }

        let isForce = e.msg.includes('强制')
        let command = 'git pull'
        let updateMsg = '执行更新操作中，请稍等...'
        if (isForce) {
            command = 'git reset --hard && git pull'
            updateMsg = `强制${updateMsg}`
        }
        e.reply(updateMsg)

        exec(command, {cwd: `${_path}/plugins/fisticuffs-plugin/`}, function (error, stdout) {
            if (/(Already up[ -]to[ -]date|已经是最新的)/.test(stdout)) {
                e.reply('目前已经是最新版互殴了~')
                return true
            }
            if (error) {
                e.reply('互殴更新失败！\nError code: ' + error.code + '\n' + error.stack + '\n 请稍后重试。')
                return true
            }
            e.reply('互殴更新成功，正在尝试重新启动Yunzai以应用更新...')
            timer && clearTimeout(timer)

            timer = setTimeout(function () {
                let command = 'npm run start'
                if (process.argv[1].includes('pm2')) {
                    command = 'npm run restart'
                }
                exec(command, function (error, stdout) {
                    if (error) {
                        e.reply('自动重启失败，请手动重启以应用新版互殴。\nError code: ' + error.code + '\n' + error.stack + '\n')
                        Bot.logger.error(`重启失败\n${error.stack}`)
                        return true
                    } else if (stdout) {
                        Bot.logger.mark('重启成功，运行已转为后台，查看日志请用命令：npm run log')
                        Bot.logger.mark('停止后台运行命令：npm stop')
                        process.exit()
                    }
                })
            }, 1000)
        })
        return true
    }
}
